<template>
	<view>
		<view class="bg sticky top-0" style="z-index: 2;">
			<!-- header -->
			<view class="all-header">
				<view :style="{height:statusBarHeight}" class="bg"></view>
				<view class="h-44p flex justify-between items-center bg px-10">
					<text class="iconfont icon-setting text-transparent" style="font-size: 24px;"></text>
					<!-- 标题 设置 -->
					<text class="text-17">账单明细</text>
					<settings @importSuccess="importSuccess"></settings>
				</view>
			</view>
			<!-- 本月结余 -->
			<view class="flex justify-between bg">
				<view class="coast flex-auto flex flex-column px-24 pt-24">
					<text class="text-24">¥&nbsp;
						<text v-show="surplus!==0" class="text-48" v-html="fmtNum(surplus,32)"></text>
						<text v-show="surplus==0" class="text-48">0.<text class="text-32">00</text></text>
					</text>
					<text style="color: #666;">月结余</text>
				</view>
				<text @click="goAccounts" class="iconfont icon-zhangbenzhangdanjizhangzhangbu rounded-30 bg p-16r mr-24 border-2 border-solid border-333" style="font-size: 30px; align-self: center;"></text>
			</view>
			<!-- 本月收入，支出，剩余预算 -->
			<view class="income flex bg p-24">
				<view class="flex flex-column mr-20r basis-1/3"  @click="handlePickerShow">
					<text class="text-14 mb-10" style="color: #666;">{{datePicker.year}}年</text>
					<text class="text-24">{{datePicker.mon}}<text class="text-14">月</text>
				<text class="iconfont icon-arrow-down"></text>&nbsp;&nbsp;|</text>
				</view>
				<view class=" basis-full flex">
					<view class="basis-1/2 flex flex-column">
						<text class="text-14 mb-10" style="color: #666;">收入</text>
						<text v-show="res.curMonIn!==0" class="text-24" v-html="fmtNum(res.curMonIn,16)"></text>
						<text v-show="res.curMonIn==0" class="text-24">0.<text class="text-16">00</text></text>
					</view>
					<view class="basis-1/2 flex flex-column">
						<text class="text-14 mb-10" style="color: #666;">支出</text>
						<text v-show="res.curMonPay!==0" class="text-24" v-html="fmtNum(res.curMonPay,16)"></text>
						<text v-show="res.curMonPay==0" class="text-24">0.<text class="text-16">00</text></text>
					</view>
				</view>
				
			</view>
			
		</view>
		<!-- 本月账单列表 -->
		<view  v-if="res.list.length>0">
			<view class="flex flex-column p-24r mb-10 bg-white" v-for="(item, index) in res.list" :key="index">
				<!-- date week pay in -->
				<view class="flex justify-between">
					<text class="mb-10 text-18">{{item.date}}
						<text class="text-999 text-14">星期{{getWeekText(item.date)}}</text>
					</text>
					<view class="text-12">
						<text v-if="getDayInOrPay(item.list).in!='0.00'" style="color: orange;">收入: {{getDayInOrPay(item.list).in}}</text>
						<text class="ml-10" v-if="getDayInOrPay(item.list).pay!='0.00'" style="color: #666;">支出: {{getDayInOrPay(item.list).pay}}</text>
					</view>
				</view>
				<!-- 当天记录 -->
				<view v-for="(acc,index) in item.list" :key="index" class="detail-item my-10">
					<!-- 左滑 编辑，删除 -->
					<uni-swipe-action-item :right-options="options" @click="onClick($event,acc)">
						<view class="flex items-center px-12" >
							<text v-if="acc.image==''" style="background-color: gold;font-size: 30px;" class="iconfont p-16r mr-20r rounded-20p" :class="acc.icon"/>
							<image v-else :src="acc.image" class="w-46p h-46p mr-20r rounded-20p" mode="aspectFill" @click="showBigImage(acc.image)"/>
							<view class="flex-auto flex flex-column content-start gap-10px">
								<text>{{acc.title}}</text>
								<text class="text-12" style="color: #999;">{{acc.time}}</text>
							</view>
							<text class="flex-auto px-6 text-14" style="color: #999;">{{acc.remark}}</text>
							<text :class="{'high':acc.type==1}">¥&nbsp;<text v-if="acc.type==0">-</text>{{formatMoney(acc.num)}}</text>
						</view>
					</uni-swipe-action-item>
				</view>
			</view>
		</view >
		<view v-else class="empty flex-auto flex flex-column justify-center items-center">
			<text class="iconfont icon-wushuju"></text>
			<text>暂无数据</text>
		</view>
		<!-- 年月选择器 -->
		<DaDatetimePicker
		    :visible="showDatePicker"
		    :value="datePickerValue"
			:format="[1,1,0,0,0,0]"
		    @confirm="handleConfirm"
		    @cancel="handleCancel"></DaDatetimePicker>
		<!-- 设置 -->
		<cover-view>
			<uni-popup ref="setPopup" type="bottom" background-color="#fff">
				<view class="flex flex-column">
					<text class="text-center py-24" style="border-bottom: 1px solid #eee;" @click="dataMigration">数据迁移</text>
					<text class="text-center py-24" >主题</text>
				</view>
			</uni-popup>
		</cover-view>
		<!-- 编辑账单记录 -->
		<setAccount :visible="showPopup" :record="record" :is-update="true" @close="showPopup=false" @updateConfirm="getData"></setAccount>
		<image v-show="isShowBigImage" :src="base64Img" mode="aspectFill" class="fixed top-0 left-0 w-100 h-100 z-3" @click="isShowBigImage=false" @longpress="saveImage"/>
	</view>
</template>

<script>
	import DaDatetimePicker from '@/components/da-datetime-picker/index.vue';
	import settings from '@/components/settings/settings.vue';
	import {getHome,delRecord} from '@/api/api.js';
	import {fmtNum,formatMoney} from '@/common/format.js';
	import { useTypeStore } from '@/store/type';
	export default {
		data() {
			return {
				// 大图
				isShowBigImage:false,
				base64Img:'',
				showDatePicker :false,
				// 日期筛选
				datePickerValue :'',
				// 账单数据
				res:{
					curMonPay:0,//本月支出
					curMonIn:0,//本月收入
					list:[],//收支明细
				},
				// 滑动操作配置
				 options:[
					{
						text: '编辑',
						style: {
							backgroundColor: '#007aff'
						}
					}, {
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				// setAccounts 属性
				record:{},
				showPopup:false,
			}
		},
		components:{DaDatetimePicker,settings},
		computed:{
			//本月结余
			surplus() {
				return this.res.curMonIn - this.res.curMonPay
			},
			// 初始化日期
			now() {
				const date = new Date()
				const year = date.getFullYear()
				const mon = (date.getMonth()+1).toString().padStart(2,'0');
				return `${year}-${mon}`
			},
			datePicker() {
				const arr = this.datePickerValue.split('-')
				return {
					year:arr[0],
					mon:arr[1]
				}
			},
			statusBarHeight() {
				return (uni.getSystemInfoSync()).statusBarHeight +'px'
			},
		},
		
		async onLoad() {
			// this.res = await getHome()
			this.datePickerValue = this.now
			await this.getData()
		},
		
		async onPullDownRefresh() {
			this.datePickerValue = this.now
			await this.getData()
			uni.stopPullDownRefresh();
		},
		setup() {
			const typeStore = useTypeStore()
			return {typeStore}
		},
		methods: {
			async importSuccess() {
				// 更新明细表
				await this.getData()
				// 更新type表
				await this.typeStore.getData()
			},
			//左滑操作 编辑/删除
			  onClick(e,obj){
				  const self = this
				  // 删除
				  if(e.content.text == '删除') {
					  uni.showModal({
					  	title:"删除",
						content:`确认删除[${obj.title}]${obj.type==0?'支出':'收入'}${obj.remark?',['+obj.remark+']':''}吗?`,
						success: async function (res) {
								if (res.confirm) {
									//todo delete
									await delRecord(obj.id)
									await self.getData()
								}
							}
					})
				  } else { //编辑
				  // console.log(obj)
						const create_time = this.datePicker.year+'-'+obj.date+' '+obj.time
						obj.create_time = create_time
						this.record = obj
						this.showPopup = true
					  
				  }
			    },
				// 显示星期
			getWeekText(mon_date) {
				const weekTxt = ['日','一','二','三','四','五','六']
				const year = this.datePickerValue.split('-')[0]
				const date = new Date(year+'-'+mon_date)
				
				return weekTxt[date.getDay()]
			},
			async getData() {
				this.res = await getHome(this.datePickerValue)
				// console.log(JSON.stringify(this.res))
			},
			handlePickerShow() {
			  this.showDatePicker = true
			  // console.log('handlePickerShow ==>')
			},
			// 显示其它日期账单详情
			async handleConfirm(v) {
			  this.datePickerValue = v
			  this.showDatePicker = false
			  await this.getData()
			  // console.log('handleConfirm ==>', v)
			},
			handleCancel() {
			  this.showDatePicker = false
			},
			goAccounts() {
				uni.navigateTo({
					url:'/pages/accounts/accountList'
				})
			},
			fmtNum(num,size) {
				return fmtNum(num,size)
			},
			formatMoney(num) {
				return formatMoney(num)
			},
			// 获取日收支
			getDayInOrPay(list) {
				const obj = {
					pay:0,
					in:0
				}
				for (let item of list) {
					item.type==1 ? obj.in += item.num : obj.pay += item.num
				}
				obj.pay =formatMoney(obj.pay);
				obj.in = formatMoney(obj.in);
				return obj
			},
			showBigImage(image) {
				this.isShowBigImage = true
				this.base64Img = image
			},
			saveImage() {
				const self = this
				uni.showActionSheet({
					itemList:['保存到相册'],
					success: function (res) {
							console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
							self.saveBaseImgFile()
						},
				})
			},
			// 将base64 图片保存到本地系统相册
			saveBaseImgFile() {
				const self = this
				const bitmap = new plus.nativeObj.Bitmap('base64')
				bitmap.loadBase64Data(this.base64Img, () => {
						const url = '_doc/' + new Date().getTime() + '.png'
						bitmap.save(
							url,
							{
								overwrite: true // 是否覆盖
								// quality: 'quality'  // 图片清晰度
							},
							(i) => {
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: () => {
										uni.showToast({
											title:'图片保存成功'
										})
										self.isShowBigImage = false
										bitmap.clear()
									}
								})
							},
							(e) => {
								uni.showToast({
									title:'图片保存失败'
								})
								bitmap.clear()
							}
						)
					},
					(e) => {
						uni.showToast({
							title:'图片保存失败'
						})
						bitmap.clear()
					}
				)
			}

		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		// justify-content: center;
	}
	
	.detail-item {
		padding-bottom: 16px;
		border-bottom: 2px dashed #eee;
		&:last-child {
			margin-bottom: 0;
			border: none;
			padding-bottom: 0;
		}
	}
	text.high {
		color: orange;
	}
	.empty {
		color: #ccc;
		.iconfont {
			font-size: 60px;
			margin-bottom: 10px;
		}
	}
</style>
